<template>
  <div class="rental-space-submission">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-indicator">数据加载中...</div>
    <div v-if="error" class="error-message">{{ error }}</div>

    <el-form
      :model="ruleForm"
      ref="ruleFormRef" 
      label-width="120px"
      class="custom-form"
      v-if="!isLoading && !error"
    >
      <el-form-item label="当前公司名称" prop="companyName">
        <el-input placeholder="路由回显公司名称" v-model="ruleForm.companyName" />
      </el-form-item>
      
      
      <!-- 间距：公司名称与空间展示区域 -->
      <div style="height: 32px;"></div>
      
       <!-- 租赁区域选择标题 -->
      <div class="section-title">
        <div class="title-line"></div>
        <span class="title-text">租赁区域选择</span>
        <div class="title-line"></div>
      </div>
      
      <div class="selection-hint">
        <i class="el-icon-info" style="color: #409EFF; margin-right: 8px;"></i>
        <span>请从下方选择需要租赁的区域</span>
        <span v-if="selectedSpaces.length > 0" class="selected-count">
          （已选择 {{ selectedSpaces.length }} 个区域）
        </span>
      </div>
      
      <!-- 间距：提示与空间展示区域 -->
      <div style="height: 16px;"></div>

      <!-- 租赁空间展示区域 -->
      <div class="space-grid">
        <div
          v-for="space in spaces"
          :key="space.unitId"
          :class="['space-item', getStatusClass(space.status), { selected: isSelected(space.unitId) }]"
          @click="handleSpaceClick(space)"
          style="pointer-events: auto;"
        >

          <div class="space-info">
            <h3>{{ getFullSpaceName(space) }}</h3>
            <p class="company-name">{{ space.name || '无公司租赁' }}</p>
            <p>状态: {{ getStatusText(space.status) }}</p>
            <p>面积: {{ space.area }} m²</p>
            <p>租金: ￥{{ space.baseRent }}/月</p>
          </div>
        </div>
      </div>

      <!-- 详情弹窗 -->
      <div v-if="selectedSpace" class="space-details-modal">
        <div class="modal-content">
          <button @click="closeDetailsModal" class="close-btn">&times;</button>
          <h2>租赁空间详情</h2>
          <p><strong>空间编号:</strong> {{ getFullSpaceName(selectedSpace) }}</p>
          <p v-if="selectedSpace.status === 0 || isSelected(selectedSpace.unitId)">
            <strong>公司名称:</strong> {{ ruleForm.companyName || '未填写公司名字' }}
          </p>
          <p v-else><strong>公司名称:</strong> {{ selectedSpace.name }}</p>
          <p><strong>租赁状态:</strong> {{ getStatusText(selectedSpace.status) }}</p>
          <p><strong>面积:</strong> {{ selectedSpace.area }} m²</p>
          <p><strong>租金:</strong> ￥{{ selectedSpace.baseRent }}/月</p>

          <p v-if="selectedSpace.status === 0 || isSelected(selectedSpace.unitId)">
            <strong>支付方式: </strong>{{ showpaymentMethod() }}
          </p>
          <p v-else><strong>支付方式: </strong>{{ getPaymentCycleText(selectedSpace.paymentCycle) }}</p>

                    <!-- 空闲：可选择或取消 -->
          <div v-if="selectedSpace.status === 0">
            <div v-if="!isSelected(selectedSpace.unitId)" style="margin-top: 20px;">
              <button type="button" @click="confirmArea(selectedSpace)" class="edit-button">
                确认选择
              </button>
            </div>
            <div v-else style="display: flex; justify-content: center; align-items: center; gap: 20px; margin-top: 20px;">
              <button type="button" @click="cancelSelected(selectedSpace)" class="edit-button" style="background-color: #e6a23c;">
                取消选择
              </button>
            </div>
          </div>

          
          <!-- 已租赁：仅展示信息，无操作，并显示租赁期限 -->
          <div v-else-if="selectedSpace.status === 1">
            <div style="margin-top: 20px; color: #999; font-size: 15px;">
              该区域已被租赁，无法进行操作。
            </div>
          </div>

          <!-- 已选中：可确定或者取消租赁期限 -->
          <div v-else-if="isSelected(selectedSpace.unitId)">
            <div style="display: flex; justify-content: center; align-items: center; gap: 40px; margin-top: 20px;">
              <button type="button" @click="confirmArea(selectedSpace)" class="edit-button" style="width: 120px;">
                确认选择
              </button>
              <button type="button" @click="cancelSelected(selectedSpace)" class="edit-button" style="width: 120px; background-color: #e6a23c; color: #fff;">
                取消选择
              </button>
            </div>
          </div>

         
        </div>
      </div>
      
      <!-- 间距：空间展示区域与提交按钮 -->
      <div style="height: 32px;"></div>

      <!-- 租赁期限的输入框 -->
      <el-form-item label="租赁期限" prop="leaseTerm">
        <el-input placeholder="请输入如下三种租赁期限的其中一种, 1年期, 2年期, 3年期" v-model="ruleForm.leaseTerm" />
      </el-form-item>

      <!-- 支付方式的下拉框 -->
      <el-form-item label="支付方式" style="margin-top: 35px;">
        <el-select v-model="paymentMethod" placeholder="请选择支付方式" style="width: 100%;">
          <el-option label="月付" value="1" />
          <el-option label="季付" value="3" />
          <el-option label="半年付" value="6" />
          <el-option label="年付" value="12" />
        </el-select>
      </el-form-item>

      <!-- 页面底部提交按钮 -->
      <div style="margin-top: 40px; text-align: center;">
        <el-button type="primary" @click="submitForm">提交</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRoute } from 'vue-router'

// 获取路由实例
const route = useRoute()
const companyIdFromRoute = ref(route.query.companyId || '')
const companyNameFromRoute = ref(route.query.companyName || '')

// 从环境变量中读取基础地址，自动适配不同环境
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

const ruleFormRef = ref(null)
const selectedSpace = ref(null)
const paymentMethod = ref('')
const isLoading = ref(false)
const error = ref(null)
const zones = ref([])

const ruleForm = ref({
  companyName: companyNameFromRoute.value, // 公司名称
  area: [],        // 选中的空间编号数组
  areaId: [],      // 选中的空间id数组
  rent: [],        // 租金数组
  size: [],        // 面积数组
  paymentCycle: [], // 支付方式数组
  leaseTerm: '',   // 租赁期限（统一）
  contractNumber: [],  // 合同编号数组
})

const spaces = ref([])
const selectedSpaces = ref([]) // 选中的空间对象数组

// 获取空间数据
const fetchSpaces = async () => {
  isLoading.value = true
  error.value = null
  
  try {
    const [spacesRes, zonesRes] = await Promise.all([
      axios.get(`${API_BASE_URL}/api/rentplaces/units`),
      axios.get(`${API_BASE_URL}/api/rentplaces/zones`)
    ])
    
    spaces.value = spacesRes.data?.data || []
    zones.value = zonesRes.data?.data || []
  } catch (err) {
    error.value = err.message || '获取数据失败'
    console.error('API错误:', err)
  } finally {
    isLoading.value = false
  }
}

// 获取完整空间名称
const getFullSpaceName = (space) => {
  if (!space) return '未知空间';
  const zone = zones.value.find(z => z.zoneId === space.zoneId);
  const zoneName = zone ? zone.zoneName : '未知';
  return `${zoneName}-${space.unitName || '未知'}`;
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '空闲',
    1: '已租赁',
    2: '维修中'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态对应的CSS类
const getStatusClass = (status) => {
  const classMap = {
    0: 'vacant',
    1: 'rented',
    2: 'maintenance'
  }
  return classMap[status] || ''
}

// 获取支付周期文本
const getPaymentCycleText = (cycle) => {
  const cycleMap = {
    1: '月付',
    3: '季付',
    6: '半年付',
    12: '年付'
  }
  return cycleMap[cycle] || `每${cycle}个月付`
}

// 点击空间卡片处理
const handleSpaceClick = (space) => {
  if (isSelected(space.unitId)) {
    // 如果已选中，则直接弹窗提示是否取消
    selectedSpace.value = { ...space }
  } else {
    showSpaceDetails(space)
  }
}


const showSpaceDetails = (space) => {
  selectedSpace.value = { ...space }
}

const showpaymentMethod = () => {
  const cycleMap = {
    '1': '月付',
    '3': '季付',
    '6': '半年付',
    '12': '年付'
  }
  return cycleMap[paymentMethod.value] || '未选择'
}

// 检查空间是否被选中
const isSelected = (unitId) => {
  return selectedSpaces.value.some(s => s.unitId === unitId)
}

// 确认选择区域
const confirmArea = (space) => {
  if (isSelected(space.unitId)) {
    ElMessage.warning('该区域已选择，无需重复选择')
    closeDetailsModal()
    return
  }

  selectedSpaces.value.push(space)

  // 更新表单数组
  ruleForm.value.area = selectedSpaces.value.map(s => getFullSpaceName(s))
  ruleForm.value.areaId = selectedSpaces.value.map(s => s.unitId)
  ruleForm.value.rent = selectedSpaces.value.map(s => s.baseRent)
  ruleForm.value.size = selectedSpaces.value.map(s => s.area)
  ruleForm.value.contractNumber = selectedSpaces.value.map(s => s.contractNumber || '')
  ruleForm.value.paymentCycle = selectedSpaces.value.map(() => paymentMethod.value)

  ElMessage.success('已确认选择区域')
  closeDetailsModal()
}


// 取消选中
const cancelSelected = (space) => {
  selectedSpaces.value = selectedSpaces.value.filter(s => s.unitId !== space.unitId)
  
  // 同步更新表单数据
  ruleForm.value.area = selectedSpaces.value.map(s => getFullSpaceName(s))
  ruleForm.value.areaId = selectedSpaces.value.map(s => s.unitId)
  ruleForm.value.rent = selectedSpaces.value.map(s => s.baseRent)
  ruleForm.value.size = selectedSpaces.value.map(s => s.area)
  ruleForm.value.contractNumber = selectedSpaces.value.map(s => s.contractNumber || '')
  ruleForm.value.paymentCycle = selectedSpaces.value.map(() => paymentMethod.value)
  
  ElMessage.success('已取消选择该区域')
  closeDetailsModal()
}


const closeDetailsModal = () => {
  selectedSpace.value = null
}

// 提交表单
const submitForm = async () => {
  if (!ruleForm.value.companyName) {
    ElMessage.error('请输入公司名称')
    return
  }
  if (!ruleForm.value.areaId.length) {
    ElMessage.error('请选择租赁空间并确认')
    return
  }
  if (!ruleForm.value.leaseTerm) {
    ElMessage.error('请选择租赁期限')
    return
  }
  if (!paymentMethod.value) {
    ElMessage.error('请选择支付方式')
    return
  }
  if (!['1年期', '2年期', '3年期'].includes(ruleForm.value.leaseTerm)) {
    ElMessage.error('租赁期限格式不正确, 请输入1年期、2年期或3年期')
    return
  }
  
  try {
    isLoading.value = true
    
    // 为每个选中的空间创建租赁请求
    const requests = selectedSpaces.value.map(space => {
      const payload = {
        unitId: space.unitId,
        
       
        status: 0, //这里还是未租赁，传递到管理端进行审核通过之后才是已经租赁
        area: space.area,
        baseRent: space.baseRent,
        
        companyId: companyIdFromRoute.value,
        paymentCycle: parseInt(paymentMethod.value),
        rentTime: ruleForm.value.leaseTerm
      }
      
      return axios.put(
        `${API_BASE_URL}/api/company/submitOtherInfo/${space.unitId}`,
        payload
      )
    })
    
    // 发送所有请求
    await Promise.all(requests)
    
    ElMessage.success('提交成功！')
    
    // 重新获取数据以更新UI
    await fetchSpaces()
    
    // 清空表单数据
    Object.assign(ruleForm.value, {
      companyName: '',
      area: [],
      areaId: [],
      rent: [],
      size: [],
      paymentCycle: [],
      leaseTerm: '',
      contractNumber: []
    })
    
    // 清空空间多选记录数组
    selectedSpaces.value = []
    paymentMethod.value = ''
    
  } catch (err) {
    error.value = '提交失败: ' + (err.response?.data?.message || err.message)
    ElMessage.error('提交失败，请重试')
  } finally {
    isLoading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSpaces()
})
</script>

<style scoped>
.loading-indicator {
  padding: 10px;
  background-color: #f0f9eb;
  color: #67c23a;
  text-align: center;
  margin-bottom: 15px;
  border-radius: 4px;
}

.error-message {
  padding: 10px;
  background-color: #fef0f0;
  color: #f56c6c;
  text-align: center;
  margin-bottom: 15px;
  border-radius: 4px;
}

.rental-space-submission {
  padding: 20px;
  font-family: 'Arial', sans-serif;
  background-color: #f8f9fa;
  max-width: 1200px;
  margin: 0 auto;
}

.custom-form {
  max-width: 800px;
  width: 100%;
  margin: 0 auto;
}

.space-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 15px;
}

.section-title {
  display: flex;
  align-items: center;
  margin: 24px 0 16px 0;
}

.title-line {
  flex: 1;
  height: 1px;
  background: linear-gradient(90deg, transparent, #dcdfe6, transparent);
}

.title-text {
  padding: 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  white-space: nowrap;
}

.selection-hint {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.selected-count {
  color: #67C23A;
  font-weight: 500;
  margin-left: 8px;
}

.space-item {
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
}

.space-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.space-item.vacant {
  border-left: 4px solid #67c23a;
}

.space-item.rented {
  border-left: 4px solid #e6a23c;
}

.space-item.maintenance {
  border-left: 4px solid #f56c6c;
}

.space-info h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
}

.space-info p {
  margin: 5px 0;
  font-size: 13px;
  color: #666;
}

.space-details-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 25px;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
}

.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  font-size: 24px;
  color: #999;
  background: none;
  border: none;
  cursor: pointer;
  padding: 5px;
}

.edit-button {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
  background-color: #409eff;
  color: white;
}

.edit-button:hover {
  background-color: #66b1ff;
}

.space-item.selected {
  outline: 3px solid #409eff;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
}

</style>